package com.retail.shopping.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.retail.common.core.domain.Result;
import com.retail.common.core.utils.StringUtils;
import com.retail.order.remote.OrderRemoteService;
import com.retail.order.vo.OrderRequest;
import com.retail.shopping.common.domain.ShoppingCart;
import com.retail.shopping.common.domain.ShoppingCartMidden;
import com.retail.shopping.common.domain.request.CartInsertRequest;
import com.retail.shopping.common.domain.response.CartListResponse;
import com.retail.shopping.server.mapper.CartMapper;
import com.retail.shopping.server.service.CartService;
import com.retail.shopping.server.service.IShoppingCartMiddenService;
import com.retail.shopping.server.service.IShoppingCartService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 功能描述:
 *
 * @version: java version 1.8
 * @author: liguangyao
 * @date: 2024-02-28 上午 10:46
 */
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private IShoppingCartService iShoppingCartService;
    @Autowired
    private IShoppingCartMiddenService iShoppingCartMiddenService;
    private static final Logger log = LoggerFactory.getLogger (CartServiceImpl.class);
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private OrderRemoteService orderRemoteService;


    private final String address = "CART_USER_ID_";

    private final String redisKey = "SHOPPING_CART:";

    //新增购物车
    @Override
    public Result cartInsert(CartInsertRequest cartInsertRequest) {
        try {
            //查询用户有没有购物车
            ShoppingCart cart = iShoppingCartService.selectShoppingFindByUserId (cartInsertRequest.getUserId ());
            String addr = address + cart.getUserId ();
            String key = redisKey + addr;
            BoundHashOperations<String, Object, Object> cartMap = redisTemplate.boundHashOps (key);

            if (cart != null) {
                cartInsertRequest.setCartId (cart.getCartId ());
                ShoppingCartMidden cartMidden = iShoppingCartMiddenService.selectCartMidden (cartInsertRequest);

                if (cartMidden != null) {
                    String cartUpd = (String) cartMap.get (cartInsertRequest.getSkuId () + "");
                    if (!StringUtils.isBlank (cartUpd)) {
                        CartListResponse cartListResponse = JSON.parseObject (cartUpd, CartListResponse.class);
                        cartListResponse.setSkuNum (cartListResponse.getSkuNum () + cartInsertRequest.getSkuNum ());
                        System.out.println (cartListResponse.getSkuTotalPrice ().toString ());
                        BigDecimal sum = cartListResponse.getSkuTotalPrice ().add (cartInsertRequest.getCartTotalPrice ());
                        cartListResponse.setSkuTotalPrice (sum);
                        cartMap.put (cartListResponse.getSkuId () + "", JSON.toJSONString (cartListResponse));
                        cartInsertRequest.setMiddenId (cartMidden.getMiddenId ());
                        iShoppingCartMiddenService.updateCartMidden (cartInsertRequest);
                        return Result.success ("加入购物车成功");
                    }
                    redisTemplate.delete (key);
                    cartInsertRequest.setMiddenId (cartMidden.getMiddenId ());
                    iShoppingCartMiddenService.updateCartMidden (cartInsertRequest);
                } else {
                    redisTemplate.delete (key);
                    iShoppingCartMiddenService.insertCartMidden (cartInsertRequest);
                }
                return Result.success ("加入购物车成功");
            } else {
                redisTemplate.delete (key);
                iShoppingCartService.shoppingCartAdd (cartInsertRequest);
                iShoppingCartMiddenService.insertCartMidden (cartInsertRequest);
                return Result.success ("新增购物车成功");
            }
        } catch (Exception e) {
            // 添加日志记录
            log.error ("新增购物车出现异常", e);
            return Result.error ("新增购物车出现异常");
        }
    }

    @Override
    public Result submitGetUUID() {
        //生成uuid
        String userKey = UUID.randomUUID ().toString ().replace ("-", "");
        //存入redis
        redisTemplate.opsForValue ().set (userKey, "", 5, TimeUnit.MINUTES);
        return Result.success (userKey);
    }

    @Override
    public Result remoteAddOrder(OrderRequest orderRequest) {
        //防重复，判断uuid存在redis里面
        if (Boolean.TRUE.equals (redisTemplate.hasKey (orderRequest.getUuid ()))) {
            //删除第一次的uuid
            redisTemplate.delete (orderRequest.getUuid ());
            //下单的业务代码
            Result result = orderRemoteService.getOrderId (orderRequest);
            return result;


        }
        //不存在则代表不是第一次，因为第一次的已经删了
        return Result.error ("禁止重复下单");
    }


//    public void recursiveMethod(int n) {
//        // 递归终止条件
//        if (n <= 0) {
//            System.out.println("递归条件不符");
//            return;
//        }
//        // 输出当前递归调用的参数
//        System.out.println("正在调用中....");
//        // 递归调用
//        recursiveMethod(n - 1);
//    }
}